package ajax;

import buffer.MessageBuffer;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import javax.security.auth.login.LoginException;
import main.Collector;
import main.Crypt;
import main.Message;
import main.User;
import html.HTML_Chat;
import html.HTML_OnlineUsers;
import java.util.Date;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import main.OnlineUsers;
import org.omg.CORBA.Current;

public enum MessagesAjaxActions {

    
    LOGIN_SEARCH {

        @Override
        public void doAction(MessagesAjaxBean bean) throws LoginException {
            String login = bean.getStringFromParam("login").trim();

            if (login == null) {
                throw new LoginException("Error");
            }

            Pattern pattern = Pattern.compile("[a-zA-Z]{5,50}");
            Matcher m = pattern.matcher(login);
            if (!m.matches()) {
                bean.addPropertyToRes("result", "login_wrong");
                return;
            }

            String message = null;

            if (Collector.isUserExists(login)) {
                message = "login_used";
            } else {
                message = "login_free";
            }
            bean.addPropertyToRes("userLogin", message);
        }
    },
    EMAIL_SEARCH {

        @Override
        public void doAction(MessagesAjaxBean bean) throws LoginException {
            String email = bean.getStringFromParam("email").trim();

            if (email == null) {
                throw new LoginException("Error");
            }

            if (email.length() > 255) {
                bean.addPropertyToRes("result", "email_wrong");
                return;
            }

            Pattern pattern = Pattern.compile("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
            Matcher m = pattern.matcher(email);
            if (!m.matches()) {
                bean.addPropertyToRes("result", "email_wrong");
                return;
            }

            String message = null;

            if (Collector.isEmailExists(email)) {
                message = "email_used";
            } else {
                message = "email_free";
            }
            bean.addPropertyToRes("userEmail", message);
        }
    },
    REGISTER {

        @Override
        public void doAction(MessagesAjaxBean bean) throws LoginException {
            String login = bean.getStringFromParam("login").trim();
            String email = bean.getStringFromParam("email").trim();
            String pass = bean.getStringFromParam("pass").trim();

            if (login == null || login.isEmpty()) {
                bean.addPropertyToRes("result", "login_empty");
                return;
            }
            if (email == null || email.isEmpty()) {
                bean.addPropertyToRes("result", "email_empty");
                return;
            }
            if (pass == null || pass.isEmpty()) {
                bean.addPropertyToRes("result", "pass_empty");
                return;
            }

            Pattern pattern = Pattern.compile("[a-zA-Z]{5,50}");
            Matcher m = pattern.matcher(login);
            if (!m.matches()) {
                bean.addPropertyToRes("result", "login_wrong");
                return;
            }

            try {
                // Шифрование пароля
                pass = Crypt.getSH1(pass);
            } catch (Exception ex) {
                bean.addPropertyToRes("result", "error");
                return;
            }

            String message = "";

            User user = new User();
            user.setLogin(login);
            user.setEmail(email);
            user.setPass(pass);

            if (Collector.addUser(user)) {
                message = "success";
            } else {
                message = "error";
            }

            bean.addPropertyToRes("result", message);
        }
    },
    LOGIN {

        @Override
        public void doAction(MessagesAjaxBean bean) throws LoginException {
            String login = bean.getStringFromParam("login").trim();
            String pass = bean.getStringFromParam("pass").trim();

            if (login == null || login.isEmpty()) {
                bean.addPropertyToRes("result", "error");
                return;
            }

            if (pass == null || pass.isEmpty()) {
                bean.addPropertyToRes("result", "error");
                return;
            }

            try {
                // Шифрование пароля
                pass = Crypt.getSH1(pass);
            } catch (Exception ex) {
                bean.addPropertyToRes("result", "error");
                return;
            }

            String message = "";
            User user = Collector.doLogin(login, pass);
            if (user.getLogin() != null) {
                
                OnlineUsers.getInstance().updateUser(user);
                //bean.setSessionParam("isAuth", "true");
                bean.setSessionParam("userInfo", user);
                message = "success";
                
                //bean.setSessionParam("isAuth", "true");
                //bean.setSessionParam("userID", user.getID());
                //bean.setSessionParam("login", login);

            } else {
                message = "error";
            }

            bean.addPropertyToRes("result", message);
        }
    },
    LOGOUT {

        @Override
        public void doAction(MessagesAjaxBean bean) throws LoginException {
            
            User user = (User)bean.getSessionParam("userInfo");
            OnlineUsers.getInstance().removeUser(user);
            //bean.setSessionParam("isAuth", "false");
            bean.setSessionParam("userInfo", null);
                
            bean.addPropertyToRes("result", "success");
        }
    },
    SEND_MSG {

        @Override
        public void doAction(MessagesAjaxBean bean) throws LoginException {
            
            String result = "";
            String text = "";
            
            User user = (User)bean.getSessionParam("userInfo");
            int userID = 0;

            if (user != null) {
                userID = user.getID();
            }
            
            if (userID != 0) {
                text = bean.getStringFromParam("text").trim();
                //(text.length() >= 3 && text.length() < 1000)
                Message msg = new Message();
                msg.setUserID(userID);
                msg.setText(text);
                Boolean res = Collector.sendMessage(msg);
                if (res) {
                    result = "success";
                } else {
                    result = "db sendMessage(msg) = false";
                }
            } else {
                result = "userID = 0";
            }
            bean.addPropertyToRes("result", result);
            MessageBuffer.doUpdate();
        }
    },
    GET_CHAT {

        @Override
        public void doAction(MessagesAjaxBean bean) throws LoginException {
            String result = "";
            try {

                User user = (User)bean.getSessionParam("userInfo");
                System.out.println("#####################################################3"+user.getEmail());
                if (user != null) {
                    ArrayList<Message> msgArray = new ArrayList<>();
                    msgArray = MessageBuffer.getInstance().getMessages();
                
                    user.setLastUpdate( new Date() );
                    OnlineUsers.getInstance().removeUser(user);
                    OnlineUsers.getInstance().updateUser(user);
                    
                    ArrayList<User> onlineUsers = new ArrayList<>();
                    onlineUsers = OnlineUsers.getInstance().getOnlineUsers();

                    /////////////////////////////
                    String html_chat = HTML_Chat.getHTML(msgArray);
                    bean.addPropertyToRes("html_chat", html_chat);

                    String html_users = HTML_OnlineUsers.getHTML(onlineUsers);
                    bean.addPropertyToRes("html_users", html_users);

                    result = "success";                    
                }
                else
                {
                    result = "session_expired";
                    bean.setSessionParam("userInfo", null);
                }
            } catch (Exception e) {
                result = "exception";
            }
            bean.addPropertyToRes("result", result);
//            if (onlineUsers.size() > 0) {
//                JsonArray jArr = new JsonArray();
//                for (int i = 0; i < onlineUsers.size(); i++) {
//                    JsonObject json = new JsonObject();
//                    json.addProperty("login", onlineUsers.get(i).getLogin());
//                    json.addProperty("avatar", onlineUsers.get(i).getImage());
//                    jArr.add(json);
//                }
//                bean.addPropertyToRes("online", jArr);
//            }
        }
    };
    private static Logger log = Logger.getLogger(MessagesAjaxActions.class.toString());
    public static MessagesAjaxActions getActionFromString(String str) throws LoginException {
        if (str != null && !str.isEmpty()) {
            if (str.equals("isLoginExists")) {
                return LOGIN_SEARCH;
            }
            if (str.equals("isEmailExists")) {
                return EMAIL_SEARCH;
            }
            if (str.equals("doRegister")) {
                return REGISTER;
            }
            if (str.equals("doLogin")) {
                return LOGIN;
            }
            if (str.equals("doLogout")) {
                return LOGOUT;
            }
            if (str.equals("sendMsg")) {
                return SEND_MSG;
            }
            if (str.equals("getChat")) {
                return GET_CHAT;
            }
        }
        throw new LoginException("Error");

    }

    public abstract void doAction(MessagesAjaxBean bean) throws LoginException;
}
